
//三种format： 0 表示解析为json对象，1 表示为responseText， 2 表示为responseXML
//element : document的某个element元素，如果format为1而且本参数不为空，那么就把返回的内容放入该元素的innerHTML中，而不再调用callback

var AjaxConnect = function (url,json,callback,format,element,interval,timeout) 
{
	this.url = url;
	this.json = json;
	this.callback = callback;
	this.xhr = null;
	this.interval = interval || 100;
	this.timeout = timeout || 100;
	this.times = 0;
	this.format = format || 0;
	this.element = element ;
	
	
	if(window.ActiveXObject) {
		this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		this.xhr = new XMLHttpRequest();
	}

}


AjaxConnect.prototype.connect = function()
{
	
		var postdata = null;
		if(this.json)
			postdata = JSON.stringify(this.json);
			
		if(postdata == null)
			this.xhr.open("GET",this.url);
		else
			this.xhr.open("POST",this.url);
		
		var x = this;
		var poll = window.setInterval(
			function(){
				if(x.xhr.readyState==4){
					window.clearInterval(poll);
					x.handleStateChange();
					x.times = 0;
				} else {
					if(x.times<x.timeout) {
						x.times ++;
					} else {
						window.alert("server response timeout!");
						window.clearInterval(poll);
						x.times = 0;
					}
				}
			}
		,this.interval);
		
		this.xhr.send(postdata);
}

AjaxConnect.prototype.handleStateChange = function()
{
	if(this.xhr.status == 200) {
		var result ;
		switch(this.format) {
			case 0:
				result = JSON.parse(this.xhr.responseText);
				if(!result) {
					window.alert("server response format error!");
				} else {
					this.callback(result);
				}
				break;
			case 1:
				result = this.xhr.responseText;
				if(this.element) {
					this.element.innerHTML = result;
				} else if(this.callback) {
					this.callback(result);
				} else {
					//nothing to do
				}
				break;
			case 2:
				result = this.xhr.responseXML;
				if(this.callback) {
					this.callback(result);
				} 
				break;
		}
	} else {
		window.alert("server resource invoke error! status=" + this.xhr.status + ",url=" + this.url);
	}
}


function loadHtmlPart(elemID,url) {
	var elem = document.getElementById(elemID);
	if(elem) {
		var conn = new AjaxConnect(url,null,null,1,elem);
		conn.connect();
	}
								   
}
